﻿#region MIT
/*
Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Drawing;
using GorgonLibrary.Graphics;
using EngineOfEvermore.Common;
using EngineOfEvermore.Imaging;

namespace EngineOfEvermore.Scene.Visual
{
    public class AnimatedSprite : AbstractSprite
    {
        #region IAnimationMap interface
        public interface IAnimationMap
        {
            FrameAnimation this[String name] { get; set; }
        }
        #endregion

        #region AnimationMap struct
        struct AnimationMap : IAnimationMap
        {
            #region Variables
            AnimatedSprite _owner;
            #endregion

            #region Constructor
            public AnimationMap( AnimatedSprite owner )
            {
                _owner = owner;
            }
            #endregion

            #region Properties
            public FrameAnimation this[String name]
            { 
                get
                {
                    FrameAnimation animation;

                    if ( _owner._animations.TryGetValue( name, out animation ) )
                    {
                        return animation;
                    }

                    return null;
                }

                set 
                {
                    if ( value == null )
                    {
                        if ( _owner._animations.ContainsKey( name ) )
                        {
                            _owner._animations.Remove( name );
                        }
                    }
                    else
                    {
                        _owner._animations[name] = value;
                    }
                }
            }
            #endregion
        }
        #endregion

        #region Variables
        FrameAnimation.Iterator _currentAnimation;
        String _currentAnimationName;
        Dictionary<String, FrameAnimation> _animations;
        Vector2d[] _subFrameVertices = new Vector2d[4];
        #endregion

        #region Properties
        public IAnimationMap Animations
        {
            get { return new AnimationMap( this ); }
        }

        public String CurrentAnimation
        {
            get { return _currentAnimationName; }
            set
            {
                if ( _currentAnimationName == value )
                    return;
                
                if ( String.IsNullOrEmpty( value ) )
                {
                    _currentAnimationName = null;
                    _currentAnimation = FrameAnimation.Iterator.Empty;
                }
                else
                {
                    Debug.Assert( _animations.ContainsKey( value ) );
                    FrameAnimation animation;

                    if ( _animations.TryGetValue( value, out animation ) )
                    {
                        _currentAnimationName = value;
                        _currentAnimation = animation.GetIterator();

                        _updateSize();
                    }
                }
            }
        }
        #endregion

        #region Constructor
        public AnimatedSprite()
        {
            _animations = new Dictionary<string, FrameAnimation>();
        }
        #endregion

        #region Methods
        public override void Draw( 
            RectangleF visibleArea, 
            GorgonLibrary.Graphics.FrameEventArgs e )
        {
            if ( _currentAnimationName == null || 
                 _currentAnimation.FrameIndex < 0 || 
                 _currentAnimation.Animation.FrameCount == 0 )
                return;

            Debug.Assert( _currentAnimation.Animation != null );

            AnimationFrame animationFrame = 
                _currentAnimation.Animation[_currentAnimation.FrameIndex];

            if ( animationFrame.SubFrameCount == 1 )
            {
                AnimationSubFrame subFrame = animationFrame[0];
                ImageMap imageMap = subFrame.ImageMap;

                Debug.Assert( imageMap != null && !imageMap.IsDisposed );
                Debug.Assert( subFrame.ImageMapFrameIndex < imageMap.FrameCount );

                imageMap.SetTextureActive( subFrame.ImageMapFrameIndex );

                if ( !_clippingActive )
                {
                    if ( !_isRotated )
                    {
                        imageMap.DrawFrame( subFrame.ImageMapFrameIndex, _aabb, FlipX,
                            FlipY, 0, _renderVertices );
                    }
                    else
                    {
                        imageMap.DrawFrame( subFrame.ImageMapFrameIndex, _worldVertices,
                            FlipX, FlipY, 0, _renderVertices );
                    }
                }
                else
                {
                    imageMap.DrawFrame( subFrame.ImageMapFrameIndex, _worldVertices,
                        FlipX, FlipY, ClipArea, 0, _renderVertices );
                }

                for ( int i = 0; i < 4; ++i )
                {
                    _renderVertices[i].Color = Color.White.ToArgb();
                }

                SlimRenderer.Instance.Smoothing = GorgonLibrary.Graphics.Smoothing.None;
                SlimRenderer.Instance.DrawVertices( _renderVertices, 0, 4 );
            }
            else
            {
                // This branch is not really optimized nor is it really tested yet
                foreach ( AnimationSubFrame subFrame in animationFrame.SubFrames )
                {
                    ImageMap imageMap = subFrame.ImageMap;

                    Debug.Assert( imageMap != null && !imageMap.IsDisposed );
                    Debug.Assert( subFrame.ImageMapFrameIndex < imageMap.FrameCount );

                    if ( !_calculateSubFrameVertices( subFrame ) )
                    {
                        continue;
                    }

                    imageMap.SetTextureActive( subFrame.ImageMapFrameIndex );
                    imageMap.DrawFrame( subFrame.ImageMapFrameIndex, _subFrameVertices, FlipX, 
                        FlipY, ClipArea, 0, _renderVertices );

                    for ( int i = 0; i < 4; ++i )
                    {
                        _renderVertices[i].Color = Color.White.ToArgb();
                    }

                    SlimRenderer.Instance.Smoothing = GorgonLibrary.Graphics.Smoothing.None;
                    SlimRenderer.Instance.DrawVertices( _renderVertices, 0, 4 );
                }
            }
        }

        public override void Update( LogicUpdateEventArgs e )
        {
            base.Update( e );

            if ( _currentAnimationName != null )
            {
                int lastIndex = _currentAnimation.FrameIndex;
                _currentAnimation.Advance( e.ElapsedTime );

                if ( _currentAnimation.FrameIndex != lastIndex )
                {
                    _updateSize();
                }
            }
        }

        /// <summary>
        /// Calculates the world positions of a subframe within the sprite.
        /// </summary>
        /// <remarks>
        /// The input vertices are read from _worldVertices field and writes the output to
        /// _subFrameVertices.
        /// </remarks>
        /// <param name="subFrame">The input sub-frame</param>
        /// <returns>Returns false if the sub-frame is invisible due to clipping.</returns>
        bool _calculateSubFrameVertices( AnimationSubFrame subFrame )
        {
            Debug.Assert( _worldVertices.Length == 4 );
            Debug.Assert( _subFrameVertices.Length == 4 );

            // Make sure this is a parallelogram
            Debug.Assert( ( _worldVertices[1] - _worldVertices[0] )
                .EpsilonEquals( _worldVertices[2] - _worldVertices[3] ) );
            Debug.Assert( ( _worldVertices[3] - _worldVertices[0] )
                .EpsilonEquals( _worldVertices[2] - _worldVertices[1] ) );

            Vector2d relativeOffset = new Vector2d( subFrame.Offset.X / this.OriginalSize.X,
                subFrame.Offset.Y / this.OriginalSize.Y );

            Size subFrameSize = subFrame.ImageMap.GetFrameSize( subFrame.ImageMapFrameIndex );

            Vector2d relativeSize = new Vector2d( subFrameSize.Width / this.OriginalSize.X,
                subFrameSize.Height / this.OriginalSize.Y );

            RectangleF intersection = new RectangleF(
                relativeOffset.X,
                relativeOffset.Y,
                relativeSize.X,
                relativeSize.Y
                );

            intersection.Intersect( ClipArea );

            if ( intersection.IsEmpty )
                return false;

            Vector2d widthVector = _worldVertices[1] - _worldVertices[0];
            Vector2d heightVector = _worldVertices[3] - _worldVertices[0];

            Vector2d relOffsetXVector;
            Vector2d relWidthVector;

            if ( !this.FlipX )
            {
                relOffsetXVector = widthVector * intersection.X;
                relWidthVector = widthVector * intersection.Width;
            }
            else
            {
                relOffsetXVector = widthVector - widthVector * intersection.X;
                relWidthVector = widthVector * -intersection.Width;
            }

            Vector2d relHeightVector;
            Vector2d relOffsetYVector;

            if ( !this.FlipY )
            {
                relOffsetYVector = heightVector * intersection.Y;
                relHeightVector = heightVector * intersection.Height;
            }
            else
            {
                relOffsetYVector = heightVector - heightVector * intersection.Y;
                relHeightVector = heightVector * -intersection.Height;
            }

            Vector2d ul = _worldVertices[0] + relOffsetXVector + relOffsetYVector;
            Vector2d ur = ul + relWidthVector;
            Vector2d lr = ur + relHeightVector;
            Vector2d ll = ul + relHeightVector;

            int outIndex = 0;
            _subFrameVertices[outIndex].X = ul.X;
            _subFrameVertices[outIndex].Y = ul.Y;
            
            ++outIndex;

            _subFrameVertices[outIndex].X = ur.X;
            _subFrameVertices[outIndex].Y = ur.Y;
            
            ++outIndex;

            _subFrameVertices[outIndex].X = lr.X;
            _subFrameVertices[outIndex].Y = lr.Y;
            
            ++outIndex;

            _subFrameVertices[outIndex].X = ll.X;
            _subFrameVertices[outIndex].Y = ll.Y;

            return true;
        }

        void _updateSize()
        {
            if ( _currentAnimation.Animation.FrameCount == 0 )
            {
                OriginalSize = Vector2d.Zero;
                return;
            }

            AnimationFrame animationFrame =
                _currentAnimation.Animation[_currentAnimation.FrameIndex];

            if ( animationFrame.SubFrameCount == 1 )
            {
                ImageMap imageMap = animationFrame[0].ImageMap;
                Size size = imageMap.GetFrameSize( animationFrame[0].ImageMapFrameIndex );
                OriginalSize = new Vector2d( size.Width, size.Height );
            }
            else
            {
                float unionLeft = float.MaxValue;
                float unionTop = float.MaxValue;
                float unionRight = float.MinValue;
                float unionBottom = float.MinValue;

                foreach ( AnimationSubFrame subFrame in animationFrame.SubFrames )
                {
                    ImageMap imageMap = subFrame.ImageMap;
                    Size size = imageMap.GetFrameSize( subFrame.ImageMapFrameIndex );
                    float subFrameRight = subFrame.Offset.X + size.Width;
                    float subFrameBottom = subFrame.Offset.Y + size.Height;

                    if ( unionLeft > subFrame.Offset.X )
                        unionLeft = subFrame.Offset.X;

                    if ( unionTop > subFrame.Offset.Y )
                        unionTop = subFrame.Offset.Y;

                    if ( unionRight < subFrameRight )
                        unionRight = subFrameRight;

                    if ( unionBottom < subFrameBottom )
                        unionBottom = subFrameBottom;
                }

                OriginalSize = new Vector2d( unionRight - unionLeft, unionBottom - unionTop );
            }
        }
        #endregion
    }
}
